import { useWorkFlowStore } from '@/store/workflowStore'
import { cloneDeep } from 'lodash'
import { workflowEditApi } from '../API'
import { graphToRunGraph } from '../compatible'

/**
 * 节点数据自动保存
 */
export const useAutoSave = () => {
  const { flow, lastFlow, flowInstance, flowVariables, disabledEdit, setUpdateTime, updateLastFlow } =
    useWorkFlowStore()
  const getMergedGraph = flowId => {
    if (!flowInstance) return
    console.log('节点数据和参数配置合并:', flowId, flowInstance.toObject(), flowVariables)
    const graph = cloneDeep(flowInstance.toObject())
    const variables = cloneDeep(flowVariables)
    // 节点参数绑定
    graph.nodes.forEach(item => {
      if (variables[item.id]) {
        // 面板参数使用flowVariables，node中可编辑data使用node数据
        item.data = {
          ...item.data,
          ...variables[item.id],
          isInIteration: item.data.isInIteration
        }
      }
    })
    // 不保存节点的动画效果
    graph.edges.forEach(item => {
      item.animated = false
    })
    return graph
  }
  const autoSave = async (flowId, force = false) => {
    if (!flowInstance) return

    if (disabledEdit) return

    const mergedGraph = getMergedGraph(flowId)
    /**
     * 更新模仿coze：比较节点，连线，配置数据是否变化，未发生变化时不进行保存（自动保存忽略放大缩小，点击，拖动节点等）
     */
    console.log('autoSave flowId, lastFlow:', mergedGraph, lastFlow)
    // if (force || shouldTriggerSave(mergedGraph, lastFlow)) {
    if (shouldTriggerSave(mergedGraph, lastFlow)) {
      const runGraph = graphToRunGraph(flow, getMergedGraph(flow.id))
      try {
        const res: any = await workflowEditApi(flowId, { graph: mergedGraph, run_graph: runGraph })
        console.log('autoSave mergedGraph, res:', mergedGraph, res)
        setUpdateTime(res.update_time.replace('T', ' '))
        updateLastFlow(res)
      } catch (error) {
        return false
      }
    }
    return true
  }
  return {
    getMergedGraph,
    autoSave
  }
}

// 移除undefined元素而是保留数组结构（即不改变数组长度和索引）
function removeUndefinedKeys(obj) {
  if (typeof obj === 'object' && obj !== null) {
    Object.keys(obj).forEach(key => {
      if (obj[key] === undefined) {
        delete obj[key]
      } else if (typeof obj[key] === 'object') {
        removeUndefinedKeys(obj[key])
      }
    })
  }
  return obj
}

function deepCompare(obj1, obj2) {
  if (obj1 === obj2) return true

  if (typeof obj1 !== 'object' || obj1 === null || typeof obj2 !== 'object' || obj2 === null) {
    return false
  }

  const keys1 = Object.keys(obj1)
  const keys2 = Object.keys(obj2)

  if (keys1.length !== keys2.length) return false

  for (const key of keys1) {
    if (!Object.prototype.hasOwnProperty.call(obj2, key) || !deepCompare(obj1[key], obj2[key])) {
      return false
    }
  }

  return true
}

function shouldTriggerSave(data1, data2) {
  // 比较 edges
  if (!deepCompare(data1.edges, data2.graph.edges)) {
    return true
  }

  if (Object.keys(data1.nodes).length !== Object.keys(data2.graph.nodes).length) {
    return true
  }

  const nodeMap = new Map()
  for (const node of data2.graph.nodes) {
    nodeMap.set(node.id, node)
  }

  // 比较 nodes
  for (const node of data1.nodes) {
    const correspondingNode = nodeMap.get(node.id)

    const cleanNode = removeUndefinedKeys(node)
    // 如果找不到对应的节点或节点的 data 不一致，则触发保存
    if (!correspondingNode || !deepCompare(cleanNode.data, correspondingNode.data)) {
      return true
    }
  }
  return false
}
